package wang.jinggo.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName: CreateHtmlUpload
 * @Description: Java 根据模板创建 html 并上传到文件服务器
 */
public class CreateHtmlUpload {

    private static final String TOEKN_HEAD = "Bearer ";

    /**
     * @param fileName 文件名称
     * @param content  内容信息
     * @return File    返回类型
     * @throws
     * @Title: MakeHtml
     * @Description: 创建html
     */
    public static File MakeHtml(String fileName, String content) {
        try {
            //设定模板文件
            String templateContent = "<html>\n" +
                    "<head>\n" +
                    "    <title>###title###</title>\n" +
                    "    <metahttp-equiv\n" +
                    "    =\"Content-Type\"content=\"text/html; charset=UTF-8\">\n" +
                    "</head>\n" +
                    "\n" +
                    "<body>\n" +
                    "<tablewidth\n" +
                    "=\"500\"border=\"0\"align=\"center\"cellpadding=\"0\"cellspacing=\"2\">\n" +
                    "<tr>\n" +
                    "    <tdalign\n" +
                    "    =\"center\"></td>\n" +
                    "</tr>\n" +
                    "<tr>\n" +
                    "    <tdalign\n" +
                    "    =\"center\"></td>\n" +
                    "</tr>\n" +
                    "<tr>\n" +
                    "    <td>###content###</td>\n" +
                    "</tr>\n" +
                    "<tr>\n" +
                    "    <td></td>\n" +
                    "</tr>\n" +
                    "\n" +
                    "</table>\n" +
                    "</body>\n" +
                    "</html>";

            templateContent = templateContent.replaceAll("###title###", fileName);
            templateContent = templateContent.replaceAll("###content###", content);
            String fileame = fileName + ".html";
            FileOutputStream fileoutputstream = new FileOutputStream(fileame);// 建立文件输出流
            byte tag_bytes[] = templateContent.getBytes("utf-8");
            fileoutputstream.write(tag_bytes);
            fileoutputstream.close();
            File file = new File(fileame);
            return file;
        } catch (Exception e) {
            System.out.print(e.toString());
        }
        return null;
    }


    /**
     * @param file    文件
     * @param Fileurl 文件服务器url
     * @return File    返回类型
     * @throws
     * @Title: 上传文件到文件服务器
     * @Description: 上传文件到文件服务器
     */

    public static String uploadFile(File file, String Fileurl, String uuid) {
        String result = "";
        OutputStream out = null;
        DataInputStream dis = null;
        try {
            // 定义数据分隔线
            String BOUNDARY = "========7d4a6d158c9";
            // 服务器的域名
            URL realurl = new URL(Fileurl);
            // 发送POST请求必须设置如下两行
            HttpURLConnection connection = (HttpURLConnection) realurl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Authorization", TOEKN_HEAD + uuid);
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            out = new DataOutputStream(connection.getOutputStream());
            // 头
            String boundary = BOUNDARY;
            // 传输内容
            StringBuffer contentBody = new StringBuffer("--" + BOUNDARY);
            // 1. 处理普通表单域(即形如key = value对)的POST请求（这里也可以循环处理多个字段，或直接给json）
            //这里看过其他的资料，都没有尝试成功是因为下面多给了个Content-Type
            //form-data  这个是form上传可以模拟任何类型
            contentBody.append("\r\n")
                    .append("Content-Disposition: form-data; name=\"")
                    .append("param" + "\"")
                    .append("\r\n")
                    .append("\r\n")
                    .append("123")
                    .append("\r\n")
                    .append("--")
                    .append(boundary);
            String boundaryMessage1 = contentBody.toString();
            out.write(boundaryMessage1.getBytes("utf-8"));
            // 2. 处理file文件的POST请求（多个file可以循环处理）
            contentBody = new StringBuffer();
            contentBody.append("\r\n")
                    .append("Content-Disposition:form-data; name=\"")
                    .append("file" + "\"; ")   // form中field的名称
                    .append("filename=\"")
                    .append(file.getName() + "\"")   //上传文件的文件名，包括目录
                    .append("\r\n")
                    .append("Content-Type:multipart/form-data")
                    .append("\r\n\r\n");
            String boundaryMessage2 = contentBody.toString();
            out.write(boundaryMessage2.getBytes("utf-8"));
            // 开始真正向服务器写文件
            dis = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[(int) file.length()];
            bytes = dis.read(bufferOut);
            out.write(bufferOut, 0, bytes);
            dis.close();
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
            out.write(endData);
            out.flush();
            out.close();
            // 4. 从服务器获得回答的内容
            String strLine = "";
            String strResponse = "";
            InputStream in = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            while ((strLine = reader.readLine()) != null) {
                strResponse += strLine + "\n";
            }
            file.delete();
            return strResponse;
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (dis != null) {
                    dis.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            file.delete();
        }
        return result;
    }
}







